<?php
header('Content-Type: text/html; charset=utf-8');
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Help Desk
 * @version 	1.0
 * @author 		Kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

/**
 * @see ZemailGateway.php
 */
require_once (dirname(__FILE__).'/../../../config/config.inc.php');
require_once (dirname(__FILE__).'/../lib/zprofess/ZadminTab.php');
require_once (dirname(__FILE__).'/../classes/ZemailGateway.php');
require_once (dirname(__FILE__).'/../classes/ZticketObject.php');
require_once (dirname(__FILE__).'/../classes/ZdepartmentObject.php');
require_once (dirname(__FILE__).'/../classes/ZpriorityObject.php');
require_once (dirname(__FILE__).'/../classes/ZticketContentObject.php');
define("NO_DEFI", 0);
define("NEW_TICKET", 1);
define("REPLY_BY_STAFF", 2);
define("REPLY_BY_CUSTOMER", 3);
define("ASSS_SATFF", 4);
$status=NEW_TICKET;
$emailGateway = new ZemailGateway();
if ($emailGateway->connectGateway($_GET))
	echo '<p>The Gateway is connect succesfully!</p>';
else
	echo '<p>The Gateway is failed connect!</p>';

$messageArr = $emailGateway->processRetriveMail();
echo "<pre>";
var_dump ($messageArr);
echo "</pre><hr /> <br />"; 
//die();

if (is_array($messageArr))
foreach ($messageArr as $message) {
	// remove [name shop]
	$message['subject'] = str_replace('['.Configuration::get('PS_SHOP_NAME').'] ','',$message['subject']);
	if (strpos($message['subject'],"Assigned: ") !== false) {
		$subject = substr($message['subject'],10);
		if (ZticketObject::getTicketForSubject ($subject)!=NULL) {
			$status = ASSS_SATFF;
			$message['subject'] = $subject; 
			echo 'Assigned-To Staff--';
		}
		else {
			$status = NEW_TICKET;
			echo 'Assigned-NewTicket--';
		}
		
	}
	
	if (strpos($message['subject'],"Re: ")!==false) {
		$subject = substr($message['subject'],4);
		if (strpos($message['subject'],'['.Configuration::get('PS_SHOP_NAME').'] ')!== false)
			$subject = substr($subject,strlen ('['.Configuration::get('PS_SHOP_NAME').'] '));
		$tiket = ZticketObject::getTicketForSubject ($subject);
		if ($tiket!=NULL) {
			if ($tiket->email_customer == $message['from']) {
				$status = REPLY_BY_CUSTOMER;
			} else 
				$status = REPLY_BY_STAFF;
			$message['subject'] =  $subject;
		}
	}
	// ticket new: stt: open
	if ($status == NEW_TICKET)
		if (ZticketObject::getTicketForSubject($message['subject'])==NULL) { // kiem tra co phai la ticket moi
			$status = NEW_TICKET;
		} else {
			$status = REPLY_BY_CUSTOMER;
		}
		
	// ticket assign to new staff
	if ($status == ASSS_SATFF) {
		$ticket = ZticketObject::getTicketForSubject ($message['subject']);
		$employee = new EmployeeCore($ticket->id_staff);
		$department = new ZdepartmentObject($ticket->id_zhelpdesk_department);
		$employee_moderator = new EmployeeCore($department->id_moderator);
		$name_moderator = $employee_moderator->firstname." ".$employee_moderator->lastname;
		$textbody = Configuration::get('ASSIGNED_TICKET_TEMPLATE',Configuration::get('PS_LANG_DEFAULT'));
		$content = ZticketContentObject::getContentNewTicket ($ticket->id_zhelpdesk_ticket);
		$words = array (
			'{name_staff}' => $employee->firstname." ".$employee->lastname,
			'{name_moderator}' => $employee_moderator->firstname." ".$employee_moderator->lastname,
			'{name_customer}' => $ticket->name_customer,
			'{email_customer}' => $ticket->email_customer,
			'{email}' => $ticket->email_customer,
			'{content}' => $content,
			'{subject}' => $subject,
			'{shop_name}' => Tools::safeOutput(Configuration::get('PS_SHOP_NAME'))
		);
		$rs = ZticketObject::sendMailTo ($employee->email,$employee->firstname,$subject,$textbody,$words);
		if ($rs)
			echo 'send assign staff okie';
	} 
	// ticket staff reply  customer| stt: pending
	else if ($status == REPLY_BY_STAFF) {
		$content = ($message['content']);
		$ticket = ZticketObject::getTicketForSubject ($message['subject']);
		$ticket->date_upd = date('Y-m-d H:i:s');
		$ticket->id_zhelpdesk_ticket_status = 3;
		$ticket->save ();
		$ticket->setMessageForTicket ($content,"",true);
		$ticket->setFileAttachmentForTicket ($message['file_attachment']);
		$textbody = Configuration::get('UD_TICKET_TEMPLATE_FOR_CUSTOMER',Configuration::get('PS_LANG_DEFAULT'));
		$words = array (
			'{name_customer}' => $ticket->name_customer,
			'{email_customer}' => $ticket->email_customer,
			'{content}' => $content,
			'{subject}' => $subject,
			'{shop_name}' => Tools::safeOutput(Configuration::get('PS_SHOP_NAME'))
		);
		$rs = ZticketObject::sendMailTo ($ticket->email_customer,'help desk',$subject,$textbody,$words);
		if ($rs)
			echo 'ticket: staff reply  customer| stt: pending';
	} 
	// ticket: customer reply  staff| stt: open
	else if ($status == REPLY_BY_CUSTOMER) {
		$ticket = ZticketObject::getTicketForSubject($message['subject']);
		$content = ($message['content']);
		$ticket->date_upd = date('Y-m-d H:i:s');
		$ticket->id_zhelpdesk_ticket_status = 1;
		$ticket->save ();
		$ticket->setMessageForTicket ($content);
		$ticket->setFileAttachmentForTicket ($message['file_attachment']);
		// ====================================== Send email for staff ======================================
		$employee = new EmployeeCore ($ticket->id_staff);
		$name = $employee->firstname." ".$employee->lastname;
		$textbody = Configuration::get('UD_TICKET_TEMPLATE_FOR_STAFF',Configuration::get('PS_LANG_DEFAULT'));
		$words = array (
			'{name_staff}' => $name,
			'{name_customer}' => $ticket->name_customer,
			'{email_customer}' => $ticket->email_customer,
			'{content}' => $content,
			'{subject}' => $ticket->subject,
			'{shop_name}' => Tools::safeOutput(Configuration::get('PS_SHOP_NAME'))
		);
		$rs = ZticketObject::sendMailTo ($employee->email,$name,$ticket->subject,$textbody,$words);
		if ($rs)
			echo 'ticket: customer reply  staff| stt: open';
		// ====================================== Send email for staff ======================================
	} else {
	// creat new ticket
		$ticket = new ZticketObject ();
		$code = ZticketObject::genCode(8);
		while (ZticketObject::testSameCode($code)!=0) {
			$code = ZticketObject::genCode(8);				
		}
		$ticket->ticket_code =  $code;// create code
		$ticket->id_zhelpdesk_department = Configuration::get('ZHELPDESK_DEFAULF_DEPARTMENT');
		$department = new ZdepartmentObject($ticket->id_zhelpdesk_department);
		$ticket->id_staff = $department->id_moderator;
		$ticket->id_zhelpdesk_ticket_status = 1;
		$ticket->id_zhelpdesk_ticket_priority = ZpriorityObject::getDefaultPriority ();
		$ticket->subject = $message['subject'];
		$ticket->email_customer = $message['from'];
		$ticket->name_customer = $message['senderName'];
		$ticket->date_add = $message['date'];
		if ($ticket->save ()) 
		{
			$content = ($message['content']);
			
			$ticket->setMessageForTicket ($content);
			$ticket->setFileAttachmentForTicket ($message['file_attachment']);
			// ====================================== Send email for moderator ======================================
			$employee = new EmployeeCore ($ticket->id_staff);
			$name = $employee->firstname." ".$employee->lastname;
			$textbody = Configuration::get('NEW_TICKET_TEMPLATE_FOR_STAFF',Configuration::get('PS_LANG_DEFAULT'));
			
			if ($textbody == '')
				$textbody = 'demodemo';
			
			$words = array (
				'{name_moderator}' => $name,
				'{name_customer}' => $ticket->name_customer,
				'{email_customer}' => $ticket->email_customer,
				'{content}' => $content,
				'{subject}' => $ticket->subject,
				'{shop_name}' => Tools::safeOutput(Configuration::get('PS_SHOP_NAME'))
			);
			
			$rs = ZticketObject::sendMailTo ($employee->email,$name,$ticket->subject,$textbody,$words);
			// ====================================== End Send emal for moderator ======================================			
		}
	}
}
